package com.app.art.security;

import cn.hutool.json.JSONUtil;
import com.atom.module.common.result.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义未登录或者token失效时的返回结果
 * 当 未认证用户（anonymous）尝试访问受保护资源 时，Spring Security 会调用此接口，决定如何“引导用户去认证”。
 * 触发时机：它只在 认证缺失 时触发，不是权限不足！
 * AuthenticationEntryPoint → 没登录（401）
 * AccessDeniedHandler → 登录了但没权限（403）
 */
@Slf4j
@Component
public class AuthenticationEntryPoint implements org.springframework.security.web.AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.info("AuthenticationEntryPoint >> {}  ",request.getRequestURI());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(Result.error(authException.getMessage())));
        response.getWriter().flush();
    }
}
